import json
import os
from selenium.webdriver.common.by import By


class JsonHandler:
    """配置文件读取工具类"""

    @staticmethod
    def read_locators(file_path: str) -> dict:
        """读取元素定位器配置文件"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                locators = json.load(f)
            # 将定位器转换为(By类型, 定位表达式)的元组形式
            return JsonHandler._convert_locators(locators)
        except FileNotFoundError:
            raise Exception(f"定位器配置文件未找到: {file_path}")

    @staticmethod
    def _convert_locators(locators: dict) -> dict:
        """将定位器配置转换为Selenium可用的格式"""
        converted = {}
        for page, elements in locators.items():
            converted[page] = {}
            for element, locator in elements.items():
                by_type, value = locator
                # 将定位器类型映射到Selenium的By类
                by_mapping = {
                    "id": By.ID,
                    "name": By.NAME,
                    "class name": By.CLASS_NAME,
                    "tag name": By.TAG_NAME,
                    "link text": By.LINK_TEXT,
                    "partial link text": By.PARTIAL_LINK_TEXT,
                    "css selector": By.CSS_SELECTOR,
                    "xpath": By.XPATH
                }
                if by_type not in by_mapping:
                    raise ValueError(f"不支持的定位器类型: {by_type}")
                converted[page][element] = by_mapping[by_type], value
        return converted


if __name__ == '__main__':
    locators = JsonHandler.read_locators(os.path.join("../configs", "locators.json"))
    print(locators)